<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.xianyuimg{
	display: inline-block;

}
.white-pink .xianyuimg img{
	width: 50px;
	height: 50px;
}


</style>
<meta charset="UTF-8">
<title>发布商品</title>

<link rel="stylesheet" href="/css/addgoods/usgoods.css" >
</head>

<body >
<div class="white-pink">

		<form id="form" name="form"  method="post"  enctype="multipart/form-data"  >
			<h1>
				发布您的二手商品
				<div  class="xianyuimg" style="display: inline-block;" >
					<img   src="images/myxianyu/myxianyu.png"  />
				</div>
			</h1>
			<label> <span id="s-span">商品描述 :</span> <textarea id="content"
					name="content"  placeholder="商 品 描 述..."></textarea>
			</label> <label> <span>商品价格 :</span> <input id="price" type="text"
				required="required" name="price" placeholder="商 品 价 格" />
			</label> <label> <span>发货地址 :</span> <input id="address" type="text"
				required="required" name="sendAddr" placeholder="发 货 地 址" />
			</label> 
			<label >  <input type="file" id="file"
				required="required" name="file" multiple="multiple" 
				onchange="read()" accept="image/jpg,image/jpeg,image/png,image/PNG">
				<input type="button" required="required" value="确认发布" id="submit">	</label> 		
		</form>
		<div id="imgDiv"><div><!-- 预览图片 -->
	</div>
</body>
<script type="text/javascript" src="js/common/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="js/common/bootstrap.js"></script>

<script>

	$(function() {
		$("body").on("click", "#submit", submit)
	});
	
	function submit() {
		console.log($("#file").val());
		if($("#content").val()=="" || $("#price").val()=="" || $("#file").val()=="" || $("#address").val()==""){
			alert("请完整的填写商品信息、价格和发货地址");
			return;
		}
		var p = /^\d+(\.\d+)?$/;
		if(!p.exec($("#price").val())){
			alert("请输入正确的价格");
			return;
		}
		var formData = new FormData();
		$.ajax({
			url : 'goods/doSaveGoods',
			type : 'POST',
			cache : false, //上传文件不需要缓存
			data : new FormData($("#form")[0]),
			processData : false, // 告诉jQuery不要去处理发送的数据
			contentType : false, // 告诉jQuery不要去设置Content-Type请求头
			success : function(data) {
				if(data.state==1){
					alert("发布成功，返回主页");
					location.href = 'index';
				}else{
					alert("发布失败，请重试");
				}
			}
		})
	}
	//可以选择多个文件加载在页面
	function read() {
		var file = document.getElementById("file");
		var imgDiv = document.getElementById("imgDiv");
		for (var i = 0; i < file.files.length; i++) {
			let reader = new FileReader();
			var file1 = file.files[i];
			reader.readAsDataURL(file1);
			reader.onload = function(result) {
				//reader对象的result属性存储流读取的数据
				imgDiv.innerHTML += '<img src="' + reader.result + '" alt=""/>'
				console.log(reader.result) // 打印出转换后的base64
			}
		}
	}
	
	
	

	
</script>


</html>